import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select,Tooltip} from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { list,del,add,edit} from "@/api/modules/tspec2015";
import { listLog,getLog,delLog,addLog,updateLog} from "@/api/tool/log";
import { groupList,listDictionary,getDictionary,delDictionary,addDictionary,updateDictionary} from "@/api/tool/dictionary"
import { upload } from "@/api/modules/common";
import { ProFormColumnsType } from '@ant-design/pro-components'

const logManagement = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [annex, setAnnex] = useState(""); 
  const [serial, setSerial] = useState("");
  const [productTypeBodyPart, setProductTypeBodyPart] = useState("");
  const [isView, SetisView] = useState(false)
  const [onReloadNum, setReloadNum] = useState(null); 
  const [isModalINCIVisible, setIsModalINCIVisible] = useState(false);
  const [typeList,setTypelist] = useState([])

  useEffect(()=>{
    getType()
  },[])

  const getType = () =>{
    const queryParams2= {
      pageNum: 1,
      pageSize: 9999,
      type:null,
    }
    groupList(queryParams2).then(res=>{
      setTypelist(res.data.rows) 
    })
  }

  const formColumns:ProFormColumnsType[] = [ {  
    title: t('log.menu'),  
    dataIndex: 'menu', // 假设这是select绑定的字段名  
    valueType: 'select', // 字段类型  
    valueEnum: {
      '安全毒理模块-报告管理': { text: '安全毒理模块-报告管理', status: '安全毒理模块-报告管理' },
      '原料管理-原料': { text: '原料管理-原料', status: '原料管理-原料' },
      '原料管理-原料功能': { text: '原料管理-原料功能', status: '原料管理-原料功能' },
      '原料管理-原料风险物质': { text: '原料管理-原料风险物质', status: '原料管理-原料风险物质' },
      '基础数据库-已使用化妆品原料目录(2021)': { text: '基础数据库-已使用化妆品原料目录(2021)', status: '基础数据库-已使用化妆品原料目录(2021)' },
      '基础数据库-2015版安全技术规范': { text: '基础数据库-2015版安全技术规范', status: '基础数据库-2015版安全技术规范' },
      '基础数据库-Ingredient文献数据库': { text: '基础数据库-Ingredient文献数据库', status: '基础数据库-Ingredient文献数据库' },
      '基础数据库-Ingredient安全信息标注': { text: '基础数据库-Ingredient安全信息标注', status: '基础数据库-Ingredient安全信息标注' },
      '基础数据库-风险物质': { text: '基础数据库-风险物质', status: '基础数据库-风险物质' },
      '基础数据库-暴露量参数': { text: '基础数据库-暴露量参数', status: '基础数据库-暴露量参数' },
      '基础数据库-参数配置': { text: '基础数据库-参数配置', status: '基础数据库-参数配置' },
    },
  },{  
    title: t('log.type'),  
    dataIndex: 'type', // 假设这是select绑定的字段名  
    valueType: 'select', // 字段类型  
    valueEnum: {
      'zy_safety_sccs_value': { text: '暴露量参数', status: '暴露量参数' },
      'zy_law_incigroup': { text: '安全技术规范组分', status: '安全技术规范组分' },
      'zy_safety_ingredient_subject_test_result': { text: '成分毒理学终点', status: '成分毒理学终点' },
      'zy_safety_function': { text: '原料功能', status: '原料功能' },
      'zy_safety_rm': { text: '原料', status: '原料' },
      'zy_product_inci_risksubstance': { text: '成分风险物质', status: '成分风险物质' },
      'zy_safety_ingredient': { text: '成分Ingredient', status: '成分Ingredient' },
      'zy_safety_rm_wording': { text: '原料话术配置', status: '原料话术配置' },
      'zy_law_inci_list': { text: '安全技术规范组分INCI清单', status: '安全技术规范组分INCI清单' },
      'zy_safety_product_fm': { text: '报告配方信息', status: '报告配方信息' },
      'zy_safety_report': { text: 'Ingredient文献数据', status: 'Ingredient文献数据' },
      'zy_safety_subject_def': { text: '毒理学终点定义', status: '毒理学终点定义' },
      'zy_law_inci': { text: '法规INCI', status: '法规INCI' },
      'zy_safety_product': { text: '报告产品信息', status: '报告产品信息' },
      'zy_safety_remark': { text: 'Ingredient附录数据', status: 'Ingredient附录数据' },
      'zy_product_risksubstance': { text: '风险物质清单', status: '风险物质清单' },
      'zy_product_rm_risksubstance': { text: '原料风险物质', status: '原料风险物质' },
      'zy_safety_function_category': { text: '原料功能大类', status: '原料功能大类' },
      'zy_safety_rm_inci': { text: '原料成分', status: '原料成分' },
    },
  },{
    title: t('log.searchValue'),
    dataIndex: 'searchValue',
    valueType: 'text', 
  }]

  const columns: any = [
    {
      title: t('log.menu'),
      dataIndex: 'menu',
      key: 'menu',
      width: 80,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (menu) => (
        <Tooltip placement="topLeft" title={menu}>
          {menu}
        </Tooltip>
      ),
    },
    {
      title: t('log.typeName'),
      dataIndex: 'typeName',
      width: 100,
      key: 'typeName',
      ellipsis: {
        showTitle: false,
      },
      render: (typeName) => (
        <Tooltip placement="topLeft" title={typeName}>
          {typeName}
        </Tooltip>
      ),
    },
    {
      title: t('log.source'),
      dataIndex: 'source',
      width: 120,
      key: 'source',
      ellipsis: {
        showTitle: false,
      },
      render: (source) => (
        <Tooltip placement="topLeft" title={source}>
          {source}
        </Tooltip>
      ),
    },
    {
      title: t('log.searchValue'),
      dataIndex: 'searchValue',
      width: 80,
      key: 'searchValue',
      ellipsis: {
        showTitle: false,
      },
      render: (text,record) => {
        let searchValue = ''; // 初始化一个用于存储搜索值的变量  
  
        if (record.operatorType === "删除") {  
          // 原始值  
          const origin = JSON.parse(record.originalValue);  
        
          typeList.forEach(k => { // 使用forEach而不是map，因为我们不需要返回新数组  
            if (record.type === k.type) {  
              let data = '';  
        
              k.dataDictionaryList.forEach(d => {  
                if (d.keyField === "Y") {  
                  for (const key in origin) {  
                    if (key === d.oriName) {  
                      data += `${d.nameCn}:${origin[key]},`;  
                    }  
                  }  
                }  
              });  
        
              if (data.length > 0) {  
                data = data.substring(0, data.length - 1); // 去除最后一个逗号  
              }  
        
              // 不直接修改record.searchValue，而是将计算后的值赋给searchValue  
              searchValue = data;  
            }  
          });  
        } else {  
          let final = JSON.parse(record.finalVlaue)
               typeList.map(k=>{
                  if(record.type==k.type){
                     let data= ""
                     k.dataDictionaryList.map(d=>{
                        if(d.keyField=="Y"){
                           for (const key in final) {
                              if(key == d.oriName){
                                 data+=d.nameCn+':'+final[key]+','
                              }
                           }
                        }
                     })
                     if(data.length>0){
                        data=data.substring(0, data.length - 1)
                     }
                     searchValue=data
                  }
               })
        }  
        
        // 使用计算后的searchValue来渲染Tooltip  
        return (  
          <Tooltip placement="topLeft" title={searchValue}>  
            {searchValue}  
          </Tooltip>  
        );  


      },
    },
    {
      title: t('log.operatorType'),
      dataIndex: 'operatorType',
      key: 'operatorType',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (operatorType) => (
        <Tooltip placement="topLeft" title={operatorType}>
          {operatorType}
        </Tooltip>
      ),
    },
    {
      title: t('log.createBy'),
      dataIndex: 'createBy',
      key: 'createBy',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (createBy) => (
        <Tooltip placement="topLeft" title={createBy}>
          {createBy}
        </Tooltip>
      ),
    },
    {
      title: t('log.createTime'),
      dataIndex: 'createTime',
      key: 'createTime',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (createTime) => (
        <Tooltip placement="topLeft" title={createTime}>
          {createTime}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      width:80,
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await listLog({...formData,  orderByColumn:'createTime',isAsc:'desc',})
    if(!success) return false
    console.log(data)
    const list2 = data.rows
    return {
      data: list2,
      total: data.total
    }
  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    if(Title=='新增/New'){
        //新增
        values.id =null
        add(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        edit(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleInci = (record) =>{
    console.log('编辑当前行数据：', record);
    const serial = record.serial;  
    const annex = record.annex
    setSerial(record.serial)
    setAnnex(record.annex)
    setProductTypeBodyPart(record.productTypeBodyPart)
    setIsModalINCIVisible(true)
    // 跳转到'/sa/addreport'路径，并带上id参数  
    // navigate(`/safety/children?serial=${serial}&annex=${annex}`); 
    
  }

  const handleView = (record) =>{
//    SetisView(true)
//    setTitle("查看/View")
//    console.log(record,'record')
//    form.setFieldsValue({ ...record });  
//    setIsModalVisible(true);  
    navigate(`/Log/logDetail?id=${record.id}`); 
  }

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        del(inciIds).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
        }) 
      },  
    }); 
  }

  const handleINCICancel = () => {  
    setIsModalINCIVisible(false);  
  };  
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const renderOperator = <>
    {/* <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button> */}
  </>
  
  return (
    <div> 
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="annex"  
              label={t('tspec2015.annex')}
              rules={[{ required: true, message: '请输入附表！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="serial"  
              label={t('tspec2015.serial')}
              rules={[{ required: true, message: '请输入序号！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="chemicalNameCn"  
              label={t('tspec2015.chemicalNameCn')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="chemicalNameEn"  
              label={t('tspec2015.chemicalNameEn')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="productTypeBodyPart"  
              label={t('tspec2015.productTypeBodyPart')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="maxConcentration"  
              label={t('tspec2015.maxConcentration')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="other"  
              label={t('tspec2015.other')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="wordConditionUseWarning"  
              label={t('tspec2015.wordConditionUseWarning')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="color"  
              label={t('tspec2015.color')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="annexDetailDesc"  
              label={t('tspec2015.annexDetailDesc')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
          </Form>  
        </Modal> 
    </div>
  )
}
export default logManagement
